package com.katsu.myviewlib.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


/**
 * Author:雅典娜
 * Created on 2024/3/8
 * 别总是抱怨生活不够幸运，是你欠了生活一份努力，
 * 每一个你讨厌的现在，都有一个不够努力的曾经，
 * 未来美不美，取决于你现在拼不拼。
 * Desc:
 * 后台:
 */
public class TextUtil {

    public static boolean isNull(String str) {
        return str == null || str.length() == 0 || str.equals("") || str.equals("null") || str.equals("NULL") || str.equals("Null");
    }

    public static boolean isNotNull(String str) {
        return !isNull(str);
    }

//
//    //<editor-fold desc="输入的文本-返回默认值">
//    public static String getInputNumber(EditNumberView editView, String defaultStr) {
//        String str = editView.getEditInfoStr();
//        String endStr = "0";
//        boolean isCanZero = false;
//        if (isNotNull(str) && str.endsWith(".")) {
//            str = str.substring(0, str.length() - 1);
//        }
//
//        if (isNotNull(str)) {
//            endStr = str;
//        }
//        if (isNotNull(defaultStr)) {
//            if (!isCanZero) {
//                if (Double.parseDouble(endStr) == 0d) {
//                    endStr = defaultStr;
//                    editView.setEditInfoStr(endStr);
//                }
//            }
//        }
//        return endStr;
//    }
//    //</editor-fold>


    /**
     * @param price 如果价格是整数  editext回显为整数 调用这个方法   （1,200.00 转换 1200）
     * @return
     */
    public static String setInputPrice(double price, int keepSize) {
        if (isNull(price + "")) {
            return "0";
        } else {
            try {
                return getEndInputPriceStr(price + "");
            } catch (Exception e) {

            }
            return "0";
        }
    }

    /**
     * @param price 如果价格是整数  editext回显为整数 调用这个方法   （1,200.00 转换 1200）
     * @return
     */
    public static String setInputPrice(String price, int keepSize) {
        if (isNull(price)) {
            return "";
        }
        price = price.replace(",", "");
        if (price.endsWith(".")) {
            price = price.substring(0, price.length() - 1);
        }
        if (price.length() == 1 && price.startsWith(".")) {
            return "";
        }
        if (isNull(price)) {
            return "";
        } else {
            DecimalFormat decimalFormat = new DecimalFormat(getPatternStr(keepSize, false));
            decimalFormat.setRoundingMode(RoundingMode.HALF_UP); //四舍五入
            return decimalFormat.format(Double.parseDouble(price));
        }
    }

    public static String getInputString(String price, int keepSize) {
        DecimalFormat decimalFormat = new DecimalFormat(getPatternStr(keepSize, false));
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP); //四舍五入
        return decimalFormat.format(Double.parseDouble(price));
    }

    //<editor-fold desc="两个数相除">
    public static String divEndValue(double value1, double value2, int keepSize) {
        double endValue = value1 / value2;
        DecimalFormat decimalFormat = new DecimalFormat(getPatternStr(keepSize, false));
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP); //四舍五入
        return decimalFormat.format(endValue);
    }
    //</editor-fold>

    //<editor-fold desc="两个数相乘">
    public static String multiEndValue(double value1, double value2, int keepSize) {
        double endValue = value1 * value2;
        DecimalFormat decimalFormat = new DecimalFormat(getPatternStr(keepSize, false));
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP); //四舍五入
        return decimalFormat.format(endValue);
    }
    //</editor-fold>


    //<editor-fold desc="设置输入框有焦点时-转化的输入价格 不带0">
    public static String getEndInputPriceStr(String inputEndPrice) {
        if (isNull(inputEndPrice)) {
            return "0";
        }
        inputEndPrice = inputEndPrice.replace(",", "");
        if (inputEndPrice.endsWith(".")) {
            inputEndPrice = inputEndPrice.substring(0, inputEndPrice.length() - 1);
        }
        if (inputEndPrice.length() == 1 && inputEndPrice.startsWith(".")) {
            return "";
        }
        if (TextUtil.isNotNull(inputEndPrice)) {
            int keepSize = 0;
            String[] p = inputEndPrice.split("\\.");
            if (p.length > 1) {
                if (Double.parseDouble(p[1]) > 0) {
                    keepSize = p[1].length();
                } else {
                    inputEndPrice = p[0];
                }
            }
            DecimalFormat decimalFormat = new DecimalFormat(getPatternStr(keepSize, false));
            decimalFormat.setRoundingMode(RoundingMode.HALF_UP); //四舍五入
            inputEndPrice = decimalFormat.format(Double.parseDouble(inputEndPrice));
            return inputEndPrice;
        } else {
            return "";
        }
    }
    //</editor-fold>

    /**
     * @param price 如果价格是整数  editext回显为整数 调用这个方法   （1,200.00 转换 1200）
     * @return
     */
    public static String setInputPrice(String price) {
        if (isNull(price)) {
            return "0";
        } else {
            if (price.endsWith(".")) {
                price = price.substring(0, price.length() - 1);
            }
            if (price.length() == 0) {
                return "0";
            }
            int keepSize = 0;
            String[] p = price.split("\\.");
            if (p.length > 1) {
                if (Double.parseDouble(p[1]) > 0) {
                    keepSize = p[1].length();
                } else {
                    price = p[0];
                }
            }

            DecimalFormat decimalFormat = new DecimalFormat(getPatternStr(keepSize, false));
            decimalFormat.setRoundingMode(RoundingMode.HALF_UP); //四舍五入
            return decimalFormat.format(Double.parseDouble(price));


        }
    }

    public static String getPriceNormal(String price) {
        if (isNull(price)) {
            return "0";
        }
        return price;
    }

    public static String getPatternStr(int keepSize, boolean isZero) {
        StringBuilder stringBuilder = new StringBuilder();
        if (keepSize > 0) {
            stringBuilder.append("0.");
            for (int i = 0; i < keepSize; i++) {
                stringBuilder.append(isZero ? "0" : "#");
            }
        } else {
            stringBuilder.append("0");
        }
        String pattern = stringBuilder.toString();
//        LogUtils.e("测试 pattern=" + pattern);
        return pattern;
    }


    public static String getEndPriceStr(String priceString, int keepSize) {
        if (isNull(priceString)) {
            return "";
        }
        priceString = priceString.replace(",", "");
        DecimalFormat decimalFormat = new DecimalFormat(getPatternStr(keepSize, false));
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP); //四舍五入
        priceString = decimalFormat.format(Double.parseDouble(priceString));
//        MyLogUtils.EJava(TextUtil.class,255,"最后 priceString=" + priceString);
        return priceString;
    }

    /**
     * @param price 返回保留两位小数的价格
     * @return
     */
    public static String getPriceString(String price, int keepSize, boolean isZero) {
        try {
            if (ObjectUtils.isEmpty(price)) {
                return "0";
            } else {
                return getPrice2(price, keepSize, isZero);
            }
        } catch (NumberFormatException e) {

        }
        return "0.00";
    }

    /**
     * @param number
     * @return
     */
    public static int getNumberNormal(String number) {
        if (ObjectUtils.isEmpty(number)) {
            return 0;
        }
        return Integer.parseInt(number);
    }

    /**
     * @param price 返回保留两位小数的价格
     * @return
     */
    public static String getPrice(String price, int keepSize) {
        if (isNull(price)) {
            return "0";
        } else {
            price = price.replace(",", "");
            DecimalFormat decimalFormat = new DecimalFormat(getPatternStr(keepSize, true));
            decimalFormat.setRoundingMode(RoundingMode.HALF_UP); //四舍五入
//            LogUtils.e("katsu getPrice ="+decimalFormat.format(Double.parseDouble(price)));
            return decimalFormat.format(Double.parseDouble(price));

        }
    }


    public static double getDoubleValue(double v, int keepSize) {
        BigDecimal bd = new BigDecimal(v);
        double value = bd.setScale(keepSize, BigDecimal.ROUND_DOWN).doubleValue();
        return value;
    }
    public static double getDoubleValue(String v, int keepSize) {
        if (ObjectUtils.isEmpty(v)){
            v ="0";
        }
        BigDecimal bd = new BigDecimal(v);
        double value = bd.setScale(keepSize, BigDecimal.ROUND_DOWN).doubleValue();
        return value;
    }

    /**
     * @param price 返回保留两位小数的价格
     * @return
     */
    public static String getPrice2(String price, int keepSize, boolean isZero) {
        if (isNull(price)) {
            return "0";
        } else {
            price = price.replace(",", "");
            DecimalFormat decimalFormat = new DecimalFormat(getPatternStr(keepSize, isZero));
            decimalFormat.setRoundingMode(RoundingMode.HALF_UP); //四舍五入
//            LogUtils.e("katsu getPrice ="+decimalFormat.format(Double.parseDouble(price)));
            return decimalFormat.format(Double.parseDouble(price));
        }
    }


    /**
     * @param decimals 返回保留两位小数的价格
     * @return
     */
    public static String getEndDecimalsNotZero(double decimals, int keepSize) {
        DecimalFormat decimalFormat = new DecimalFormat(getPatternStr(keepSize, false));
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP); //四舍五入
        return decimalFormat.format(decimals);
    }

    public static String getFormatNumber(double d, int keepSize) {
        DecimalFormat decimalFormat = new DecimalFormat(getPatternStr(keepSize, true));
        decimalFormat.setRoundingMode(RoundingMode.HALF_UP); //四舍五入
        return decimalFormat.format(d);

//        NumberFormat nf = NumberFormat.getNumberInstance(); //带千分位符号
//        // 保留3位小数
//        nf.setMaximumFractionDigits(keepSize);
//        // 如果不需要四舍五入，可以使用RoundingMode.DOWN
//        nf.setRoundingMode(RoundingMode.UP);
//
//        return nf.format(d);
    }


    public static String getFormat(double d, int keepSize) {
        String str = String.format("%." + keepSize + "f", d);
        return str;
    }


    /**
     * @param text
     * @return String  返回类型
     * @Title: fmtMicrometer
     * @Description: 格式化数字为千分位
     */
    public static String fmtMicrometer(String text) {
        LogUtils.d("转化前" + text);
        if (ObjectUtils.isEmpty(text)) {
            return "0.00";
        }
        NumberFormat currency = NumberFormat.getCurrencyInstance();//带人民币符号
        BigDecimal price = new BigDecimal(text);
        currency.setMaximumFractionDigits(2);
        String price2 = currency.format(price);
        currency.setGroupingUsed(true); //去掉千分位符号   true则显示千分位符号
        if (price2.startsWith("-")) {
            text = "-" + price2.substring(2, price2.length());
        } else {
            text = price2.substring(1, price2.length());
        }
//        LogUtils.d("转化后" + text);
        return text;
    }

    /**
     * @param text
     * @return String  返回类型
     * @Title: fmtMicrometer
     * @Description: 格式化数字为千分位
     */
    public static String fmtMicrometer(String text, int keepSize) {
        LogUtils.d("转化前" + text);
        if (ObjectUtils.isEmpty(text)) {
            return "0.00";
        }
        if (text.endsWith(".")) {
            text = text.substring(0, text.length() - 1);
        }
        NumberFormat currency = NumberFormat.getCurrencyInstance();//带人民币符号
        BigDecimal price = new BigDecimal(text); //.stripTrailingZeros() 去掉后面的0
        currency.setMaximumFractionDigits(keepSize != 2 ? keepSize : 2);
        String price2 = currency.format(price);
        currency.setGroupingUsed(true); //去掉千分位符号   true则显示千分位符号
        if (price2.startsWith("-")) {
            text = "-" + price2.substring(2);
        } else {
            text = price2.substring(1);
        }

//        LogUtils.e("最后的价格="+getEndPriceStr(text,keepSize));
        return text;
    }



    public static int dp2px(Context context, float dp) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5);
    }

    // 根据手机的分辨率从 px(像素) 的单位 转成为 dp
    public static int px2dip(Context context,float pxValue) {
        // 获取当前手机的像素密度（1个dp对应几个px）
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f); // 四舍五入取整
    }

    public static int px2dp(Context context,int px) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (px / density + 0.5);
    }

    public static void setEditextFocus(EditText editText, boolean isEdit) {
        editText.setCursorVisible(isEdit);
        editText.setFocusable(isEdit);
        editText.setFocusableInTouchMode(isEdit);
    }

    /**
     * 替换字符串
     *
     * @param str     待处理字符串
     * @param suffix  匹配判断字符串
     * @param replace 替换的内容
     * @return 处理后的字符串
     */
    public static String replaceAll(final String str, final String suffix, final String replace) {
        // 如果替换的内容或者判断的字符串为 null, 则直接跳过
        if (!ObjectUtils.isEmpty(str) && !ObjectUtils.isEmpty(suffix) && replace != null && !suffix.equals(replace)) {
            try {
                return str.replaceAll(suffix, replace);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    // 换行字符串
    public static final String NEW_LINE_STR = System.getProperty("line.separator");

    /**
     * 清空字符串全部换行符
     *
     * @param str 待处理字符串
     * @return 处理后的字符串
     */
    public static String clearLine(final String str) {
        return replaceAll(str, NEW_LINE_STR, "");
    }

    public static String setClearSpaceTextStr(String str) {
        String endString = "";
        try {
            if (!isNull(str)) {
                endString = clearLine(str);
            }
        } catch (Exception e) {
        }
        return str.replaceAll("\\s+", "");

    }

    //TODO 设置文字 判空
    public static String setTextStr(String str) {
        String endString = "";
        try {
            if (!isNull(str)) {
                endString = clearLine(str);
            }
        } catch (Exception e) {
        }
        return endString;
    }





    //<editor-fold desc="设置保留几位小数">
    public static String getDecimal(String d, int keepSize) {
        if (ObjectUtils.isEmpty(d)) {
            return "0";
        }
        BigDecimal bigDecimal = new BigDecimal(d).setScale(keepSize, BigDecimal.ROUND_HALF_UP);
        double n = bigDecimal.doubleValue();
        boolean t = n == (int) n;
        if (t) {
            return String.valueOf((int) n);
        }
        return bigDecimal.toPlainString();
    }

    public static String getDecimal(double d, int keepSize) {
        if (ObjectUtils.isEmpty(d)) {
            return "0";
        }
        BigDecimal bigDecimal = new BigDecimal(d).setScale(keepSize, BigDecimal.ROUND_HALF_UP);
        double n = bigDecimal.doubleValue();
        boolean t = n == (int) n;
        if (t) {
            return String.valueOf((int) n);
        }
        return bigDecimal.toPlainString();
    }

    //</editor-fold>

    //<editor-fold desc="读取Json文件的工具类">
    public static String getAssetJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
    //</editor-fold>



    /**
     * @param context
     * @param textView
     * @param type     0 左 1 上 2 右 3下
     * @param resImg   0 不显示图标
     */
    public static void setTextImg(Context context, TextView textView, int type, int resImg) {
        if (resImg == 0) {
            textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
            textView.setCompoundDrawablePadding(ConvertUtils.dp2px(0f));
            return;
        }
        Drawable drawable = context.getResources().getDrawable(resImg);
        textView.setCompoundDrawablesWithIntrinsicBounds(type == 0 ? drawable : null, type == 1 ? drawable : null, type == 2 ? drawable : null,
                type == 3 ? drawable : null);
        textView.setCompoundDrawablePadding(ConvertUtils.dp2px(6f));
    }

    /**
     * @param context
     * @param textView
     * @param type     0 左 1 上 2 右 3下
     * @param resImg   0 不显示图标
     */
    public static void setTextImg(Context context, TextView textView, int type, int resImg, float padding) {
        if (resImg == 0) {
            textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
            textView.setCompoundDrawablePadding(ConvertUtils.dp2px(0f));
            return;
        }
        Drawable drawable = context.getResources().getDrawable(resImg);
        textView.setCompoundDrawablesWithIntrinsicBounds(type == 0 ? drawable : null, type == 1 ? drawable : null, type == 2 ? drawable : null,
                type == 3 ? drawable : null);
        textView.setCompoundDrawablePadding(ConvertUtils.dp2px(padding));
    }






    //<editor-fold desc="根据字符串指定位数截取，组成数组">

    /**
     * @param str
     * @param len 每len（2）位一截取
     * @return
     */
    public static List<String> getSubList(String str, int len) {
        List<String> list = new ArrayList<>();
        if (isNull(str)) {
            return list;
        }
        if (str.length() <= len) {
            list.add(str);
            return list;
        }
        int index = 0;
        // 01100001
        int size = (int) Math.ceil(str.length() / len);  //
        boolean isEnd = str.length() % len == 0;
        for (int i = 0; i < size; i++) {
            list.add(str.substring(index, index + len));
            index += len;
        }
        if (!isEnd) {
            list.add(str.substring(index));
        }
        return list;
    }
    //</editor-fold>


    /**
     * @state 00不下肥，01下肥，10堵肥
     */
    public static String getStatusStr(String state) {
        switch (state) {
            case "00": {
                return "不下肥";

            }
            case "01": {
                return "下肥";
            }
            case "10": {
                return "堵肥";
            }
        }
        return "";
    }


    //<editor-fold desc="获取 施肥监控状态名称">
    public static List<String> getStateSubList(String str, int len) {
        List<String> list = new ArrayList<>();
        if (isNull(str)) {
            return list;
        }
        if (str.length() <= len) {
            list.add(str);
            return list;
        }
        int index = 0;
        // 01100001
        int size = (int) Math.ceil(str.length() / len);  //
        boolean isEnd = str.length() % len == 0;
        for (int i = 0; i < size; i++) {
            list.add(getStatusStr(str.substring(index, index + len)));
            index += len;
        }
        if (!isEnd) {
            list.add(str.substring(index));
        }
        return list;
    }
    //</editor-fold>


    //<editor-fold desc="每公顷多少株计算，返回株数">

    /**
     * @param newScale 保留几位小数
     * @param data     数据
     */
    public static String getTextScaleData(String data, int newScale) {
        BigDecimal b = new BigDecimal(data);
        float endValue = b.setScale(newScale, BigDecimal.ROUND_HALF_UP).floatValue();
//        LogUtils.e("katsu 转换的 data="+data +"   endValue ="+endValue);
        String endStr = String.valueOf(endValue);
        if (endStr.endsWith(".0")) {
            return endStr.substring(0, endStr.length() - 2);
        }
        if (endStr.endsWith(".00")) {
            return endStr.substring(0, endStr.length() - 3);
        }
        if (endStr.endsWith(".000")) {
            return endStr.substring(0, endStr.length() - 4);
        }
        return endStr;
    }
    //</editor-fold>

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void getAESData(String key) {
        byte[] keyBytes = Base64.getDecoder().decode(key); //xCC1Xr6xYkOAnxPS6V08w==
        SecretKey originalKey = new SecretKeySpec(keyBytes, 0, keyBytes.length, "AES");
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static String decrypt(String ciphertext, SecretKey key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decodedBytes = Base64.getDecoder().decode(ciphertext);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes);
    }

    //<editor-fold desc="获取字符串中,第个n逗号的位置">
    public static int findNthComma(String str, int n) {
        int count = 0;//记录逗号的个数
        int index = -1;//记录逗号的位置
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ',') {
                count++;
                if (count == n) {
                    index = i;
                    break;
                }
            }
        }
        return index;
    }
    //</editor-fold>

}
